package rt2

import (
	"fmt"

	"gitee.com/zhang-li17/rt2/pcol"

	"github.com/google/uuid"
	"github.com/sirupsen/logrus"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func (c *ClientHandler) handleResValSetResponse(f *Frame, res *pcol.ResValSetResponse) {
	if !res.Ok {
		c.handleNewEvent(pcol.EventType_SET_RES_FAILED, pcol.EventLevel_ERROR, res.ErrMsg, f.Payload)
	} else {
		logrus.Info(res)
	}
}

func (c *ClientHandler) handleResValResponse(res *pcol.ResValResponse) {
	if !res.Ok {
		c.handleNewEvent(pcol.EventType_GET_RES_FAILED, pcol.EventLevel_ERROR, res.ErrMsg, nil)
	} else {
		logrus.Info(res)
		for _, r := range res.Res {
			e := c.addOrUpdateRes(r)
			if e != nil {
				logrus.Error(e)
			}
		}
	}
}

func (c *ClientHandler) newEvent(evtType pcol.EventType, evtLevel pcol.EventLevel, description string, data []byte) *pcol.Event {
	return &pcol.Event{
		Id:          uuid.New().String(),
		Type:        evtType,
		Level:       evtLevel,
		Description: description,
		Data:        data,
		Timestamp:   timestamppb.Now(),
		Source:      c.Name(),
	}
}
func (c *ClientHandler) handleNewEvent(evtType pcol.EventType, evtLevel pcol.EventLevel, description string, data []byte) {
	c.handleEvent(c.newEvent(evtType, evtLevel, description, data))
}

func (c *ClientHandler) handleCancelResValResponse(res *pcol.ResValResponse) {
	if !res.Ok {
		c.handleNewEvent(pcol.EventType_CANCEL_RES_FAILED, pcol.EventLevel_ERROR, res.ErrMsg, nil)
	} else {
		logrus.Info(res)
	}
}

func (c *ClientHandler) handleEvent(evt *pcol.Event) {
	evtChan <- evt
}

func (c *ClientHandler) handleResValRequest(f *Frame, req *pcol.ResValRequest) {

	// 判断请求参数
	// if len(req.Names) == 0 {
	// 	response := pcol.ResValResponse{
	// 		Ok:     false,
	// 		ErrMsg: "no resource name",
	// 	}
	// 	err := SendProtoMsg(c.client, pcol.MessageType_RES_VAL_RESPONSE, &response)
	// 	if err != nil {
	// 		logrus.Error(err)
	// 	}
	// 	return
	// }
	cnt := req.MaxReplyTimes
	// 当间隔设置为负数时，只回复一次
	if req.Interval < 0 {
		cnt = 1
	} else if cnt == 0 {
		// 当间隔设置为0时，持续回复，直到接收到取消获取资源指令
		cnt = -1
	}
	// fmt.Println("如果Names不为空,判断资源是否存在")
	// 判断资源是否存在
	if len(req.Names) != 0 {
		for _, name := range req.Names {
			if _, ok := c.resMap[name]; !ok {
				response := pcol.ResValResponse{
					Ok:     false,
					ErrMsg: fmt.Sprintf("resource %s not found", name),
				}
				err := SendProtoMsg(c.client, pcol.MessageType_RES_VAL_RESPONSE, &response)
				if err != nil {
					logrus.Error(err)
				}
				fmt.Print("res error")
				return
			}
		}
	}
	// 所有资源均存在，构造任务数据
	d := &ResReqMissionData{
		names:           req.Names,
		intv:            req.Interval,
		totalReplyTimes: cnt,
		replyTimes:      0,
		seq:             f.Seq,
	}
	// 添加任务，后续执行由通道触发
	c.resReqMissionManager.Add(d)
	// fmt.Print("c.resReqMissionManager.Add(d)")
}

func (c *ClientHandler) handleCancelResValRequest(f *Frame, req *pcol.ResValRequest) {
	d, err := c.resReqMissionManager.Remove(req.GroupId)
	rep := &pcol.ResValResponse{}

	if err != nil {
		rep.Ok = false
		rep.ErrMsg = err.Error()
	} else {
		rep.Ok = true
		rep.GroupId = d.groupId
		rep.Interval = d.intv
		rep.MaxReplyTimes = d.totalReplyTimes
	}
	SendProtoMsgWithSeq(c.client, pcol.MessageType_RES_VAL_RESPONSE, rep, f.Seq)
}

func (c *ClientHandler) handleResValSetRequest(f *Frame, req *pcol.ResValSetRequest) {
	// TODO 完成资源设置指令
}
